var Entry = require('../lib/entry');

exports.list = function(req, res, next) {
  var page = req.page;
  Entry.getRange(page.from, page.to, function(err, entries) { // 获取消息
    if (err) return next(err);
    res.render('entries', { // 渲染HTTP响应
      title: 'Entries',
      entries: entries
    });
  });
};

exports.form = function(req, res) {
  res.render('post', { title: 'Post' });
};

/**
 * 用从表单中提交上来的数据创建消息
 */
exports.submit = function(req, res, next) {
  var data = req.body;

  if (!data.title) {
    res.error("Title is required.");
    res.redirect('back');
    return;
  }

  if (data.title.length < 4) {
    res.error("Title must be logger than 4 characters.");
    res.redirect('back');
    return;
  }

  var entry = new Entry({
    "username": res.locals.user.name,
    "title": data.title,
    "body": data.body
  });

  entry.save(function(err) {
    if (err) return next(err);
    if (req.remoteUser) {
      res.json({message: 'Entry added.'});
    } else {
      res.redirect('/');
    }
  });
};
